package de.ret_world.openrpgstudio.mapeditor.scripts;

import de.ret_world.openrpgstudio.editor.Database;
import de.ret_world.openrpgstudio.editor.Project;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.TwoArgFunction;

/**
 * The TileMap Lua Library for working with TileMaps through Lua code.
 *
 * @author Emu
 */
public class TileMapLib extends TwoArgFunction {

    @Override
    public LuaValue call(LuaValue arg1, LuaValue arg2) {
        Database database = Project.getInstance().getDatabase();
        switch (opcode) {
            case 0: {
                LuaValue t = tableOf();
                this.bind(t, TileMapLib.class, new String[]{"newTilemap", "changeTilemap", "getTilemap"}, 1);
                env.set("Tilemaps", t);
                return t;
            }
            case 1: //newTilemap
                if (arg1.istable()) {
                    TileMap tm = new TileMap();
                    tm.create(arg1);
                    database.putScriptObject(TileMap.TYPE, tm.getID(), tm);
                } else {
                    return error("no table: " + arg1);
                }
                return NIL;
            case 2: //changeTilemap
                if (arg1.isstring()) {
                    TileMap tm = (TileMap) database.getScriptObject(TileMap.TYPE, arg1.toString());
                    if (tm == null) {
                        return error("no such Tileset found unter: " + arg1);
                    }
                    if (arg2.istable()) {
                        tm.create(arg2);
                    } else {
                        return error("no table: " + arg2);
                    }
                } else {
                    return error("no string: " + arg1);
                }
                return NIL;
            case 3: //ngetTilemap
                if (arg1.isstring()) {
                    TileMap tm = (TileMap) database.getScriptObject(TileMap.TYPE, arg1.toString());
                    if (tm == null) {
                        return error("no such Tileset found unter: " + arg1);
                    } else {
                        return tm.toLua();
                    }
                }
                return NIL;
            default:
                return error("bad opcode: " + opcode);
        }
    }
}
